"""
命名空间与作用域
"""
import sys


#
# def scope_test():
#     def do_local():
#         spam = "local spam"
#     def do_nonlocal():
#         nonlocal spam
#         spam = "nonlocal spam"
#     def do_global():
#         global spam
#         spam="global spam"
#     spam = "test spam"
#     do_local()
#     print("After local assignment:" , spam)
#     do_nonlocal()
#     print("After nonlocal assignment:" , spam)
#     do_global()
#     print("After global assignment:" , spam)
# scope_test()
# print("In global scope:" , spam)
class ClassName:
    pass
class MyClass:
    #a simple example calss
    i=123456
    data=[1,2,3,4,5]
    def f(self):
        return 'hello world'
    def __init__(self):
        self.data=[]
x = MyClass()
#创建类的新实例，并将此对象分配给本地变量x
# print(x.i)
# print(x.f())
"""
实例化操作创建一个空对象。许多喜欢使用针对特定实例自定义的实例创建对象初始状态。，因此，一个类可以定义一个名为_init_()特殊方法
当类定义方法时，类实例化自动调用新创建的类实例。
"""
class Complex:
    def __init__(self , realpart , imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(2.0 , -3.4)
print(x.r , x.i )
"""
实例对象是属性引用。 有两种有效的属性名称：数据属性和方法
"""
# x.counter = 1
# while x.counter < 10:
#     x.counter = x.counter * 2
# print(x.counter)
# del x.counter

# class Dog:
#     kind = 'canine'
#
#     def __init__(self , name ):
#         self.name = name
#
# d=Dog('Fido')
# e=Dog('Buddy')
# print(d.kind)
# print(d.name)
# print(e.name)
"""

class Dog:
    tricks=[]
    def __init__(self,name):
        self.name = name
    def add_trick(self , trick):
        self.tricks.append(trick)

d = Dog("fido")
e=Dog("Buddy")
d.add_trick("roll over")
e.add_trick("play dead")
print(d.tricks)

class Cat:
    def __init__(self,name):
        self.name = name
        self.tricks=[]
    def add_trick(self , trick):
        self.tricks.append(trick)
d = Cat("Fido")
e = Cat("Buddy")
d.add_trick("roll over")
e.add_trick("play dead")
print(d.tricks)
"""

# class WareHouse:
#     purpose = 'storage'
#     region = 'west'
# w1 = WareHouse()
# print(w1.purpose , w1.region)
#
# w2 = WareHouse()
# w2.region='east'
# print(w2.purpose , w2.region)

# def f1(self , x , y):
#     return min(x , x+y)
# class C:
#     f=f1
#     def g(self):
#         return 'hello world'
#     h = g
# class Bag:
#     def __init__(self):
#         self.data=[]
#     def add(self,x):
#         self.data.append(x)
#     def addtwice(self,x):
#         self.add(x)
#         self.add(x)
# class DerivedClassName(BaseClassName):
#     pass
# class DerivedClassName(modname.BaseClassName):
"""

class Mapping:
    def __init__(self, iterable):
        print("Mapping init")
        self.items_list=[]
        self.__update(iterable)
    def update(self,iterable):
        print("Mapping.update")
        for item in iterable:
            self.items_list.append(item)
    __update = update
class MappingSubClass(Mapping):
    def update(self, keys , values):
        print("MappingSubClass.update")
        for item in zip(keys, values):
            self.items_list.append(item)
a = MappingSubClass('abc')
a.update([1,2,3],[4,5,6])
"""

from dataclasses import dataclass
@dataclass
class Employee:
    name: str
    dept: str
    salary: int
john = Employee('john', 'computer lab' , 2021)
print(john.dept , john.salary)

# for element in [1,2,3]:
#     print(element)
# for element in (1,2,3):
#     print(element)
# for key in {'one':1 , 'two':2}:
#     print(key)
# for char in "123":
#     print(char)
# for line in open("D:\\test\\test.txt"):
#     print(line , end='')
"""

s = 'abc'
it = iter(s)
print(next(it))
print(next(it))
print(next(it))
class Reverse:
    def __init__(self,data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index-1
        return self.data[self.index]
    def reverse(self,data):
        for index in range(len(data)-1,-1,-1):
            yield data[index]
rev = Reverse('spamgolf')
# iter(rev)
for char in rev:
    print(char)
"""
# print(sum(i*i for i in range(10)))
# xvec = [10,20,30]
# yvec = [7,5,3]
# print(sum(x*y for x,y in zip(xvec,yvec)))

# unique_words = set(word for line in page for word in line.split())

# valedictorian = max((student.gpa , student.name) for student in graduaates)

# data = 'golf'
# a = list(print("i=" ,i , data[i]) for i in range(len(data)-1 , -1 , -1))
# for i in range(5 , -1 , -1):
#     print(i)

import os
print(os.getcwd())
# os.chdir("./server/accesslogs")
# os.system('ping')
# print(dir(os))
# print(help(os))

import shutil
# shutil.copyfile("D:\\test\\1.txt" , "D:\\test\\2.txt")
# shutil.move("D:\\test\\1.txt" , "D:\\test\\3.txt")

import glob
a = glob.glob('*.py')
# print(a)
# print(sys.argv)

import argparse
# parser = argparse.ArgumentParser(
#     prog='top',
#     description='Show top lines from each file')
# parser.add_argument('filenames' , nargs='+')
# parser.add_argument('-l' , '--lines' , type=int , default=10)
# args=parser.parse_args()
# print(args)
# sys.stderr.write("Warning , log file not found  starting a new one \n")

import re
# a = re.findall(r'\bf[a-z]*' , 'which foot or hand fell fastest')
# print(a)
# a = re.sub(r'(\b[a-z]+) \1' , r'\1' , 'cat in the the hat')
# print(a)
# a = 'tea for too'
# b = a.replace('too' , 'two')
# print(b)
import  math
# a = math.cos(math.pi / 4)
# print(a)
# print(math.log(1024 , 2))
# print(2**10)
import random
# a = random.choice(['apple' , 'pear' , 'banana'])
# print(a)
# random.random()
# print(random.randrange(5))

import statistics
# data=[2.43,1.82,3.22,1.2 , 0.3 , 0.45 , 3.5]
# print(statistics.mean(data))
# print(statistics.median(data))
# print(statistics.variance(data))

from urllib.request import urlopen
# with urlopen("http://worldtimeapi.org/api/timezone/etc/UTC.txt") as response:
#     for line in response:
#         line=line.decode()
#         if line.startswith('datetime'):
#             print(line.rstrip())
import smtplib
# server = smtplib.SMTP("localhost")
# server.sendmail("jiawenyao401@sina.com")
# server.quit()

from datetime import date
# now = date.today()
# print(now)
#
# print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B"))
# birthday= date(1923,7,31)
# age = now -birthday
# print(age.days)

import zlib
# s = b'witch which has which witches wrist watch'
# print(len(s))
# t = zlib.compress(s)
# print(t , len(t))
# a =zlib.decompress(t)
# print(a)
# b = zlib.crc32(s)
# print(b)

from timeit import Timer
# a = Timer('t=a; a=b; b=t' , 'a=1;b=2').timeit()
# print(a)
# b=Timer('a,b = b,a ' , 'a=1;b=2').timeit()
# print(b)
def average(values):
    return sum(values) / len(values)
import  doctest
doctest.testmod()

import unittest
class TestStatisticalFunctions(unittest.TestCase):
    def test_average(self):
        self.assertEqual(average([20,30,70]) , 40.0)
        self.assertEqual(round(average([1,5,7]),1) , 4.3)
        with self.assertRaises(ZeroDivisionError):
            average([])
        with self.assertRaises(TypeError):
            average(20,30,70)
unittest.main()